//
//  DSContentView.m
//  DemoTest
//
//  Created by DaShuEdu on 2017/5/12.
//  Copyright © 2017年 DaShuEdu. All rights reserved.
//

#import "DSContentView.h"

static NSString *kContentCellID = @"kContentCellID";

@interface DSContentView () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) NSArray *childVcs;
@property (nonatomic, strong) UIViewController *parentVc;
@property (nonatomic, assign) CGFloat startOffsetX;
@property (nonatomic, assign) BOOL isForbidDelegate;
@property (nonatomic, strong) UICollectionView *collectionView;

@end

@implementation DSContentView

- (instancetype)initWithFrame:(CGRect)frame
                     childVcs:(NSArray<UIViewController *> *)childVcs
                     parentVc:(UIViewController *)parentVc
{
    if (self = [super initWithFrame:frame]) {
        self.childVcs = childVcs;
        self.parentVc = parentVc;
        self.startOffsetX = 0;
        [self setupUI];
    }
    return self;
}

#pragma mark - UI
- (void)setupUI {
    [self addSubview:self.collectionView];
    
    for (UIViewController *childVc in self.childVcs) {
        [self.parentVc addChildViewController:childVc];
    }
}

#pragma mark - Lazy
- (UICollectionView *)collectionView {
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = self.bounds.size;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.pagingEnabled = YES;
        _collectionView.scrollsToTop = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.bounces = NO;
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:kContentCellID];
    }
    return _collectionView;
}

#pragma mark - UICollectionDataSource 
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.childVcs.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kContentCellID forIndexPath:indexPath];
    for (UIView *subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    UIViewController *childVc = self.childVcs[indexPath.item];
    childVc.view.frame = cell.contentView.bounds;
    [cell.contentView addSubview:childVc.view];
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self collectionViewDidEndScroll];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (decelerate) {
        [self collectionViewDidEndScroll];
    }
}

- (void)collectionViewDidEndScroll {
    NSInteger inIndex = (NSInteger)(self.collectionView.contentOffset.x / self.collectionView.bounds.size.width);
    if ([self.delegate respondsToSelector:@selector(contentViewWith:inIndex:)]) {
        [self.delegate contentViewWith:self inIndex:inIndex];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.isForbidDelegate = NO;
    self.startOffsetX = scrollView.contentOffset.x;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.x == self.startOffsetX || self.isForbidDelegate) {
        return;
    }
    
    CGFloat progress = 0;
    NSInteger targetIndex = 0;
    NSInteger sourceIndex = 0;
    
    NSLog(@"offset.x:%f ----floor:%d ----/:%d ----progress:%f",
          scrollView.contentOffset.x,
          ((int)floor(scrollView.contentOffset.x)),
          (((int)floor(scrollView.contentOffset.x))/((int)scrollView.bounds.size.width)),
          scrollView.contentOffset.x-(((int)floor(scrollView.contentOffset.x))/((int)scrollView.bounds.size.width))*self.collectionView.bounds.size.width);
    
    progress = (scrollView.contentOffset.x-(((int)floor(scrollView.contentOffset.x))/((int)scrollView.bounds.size.width))*self.collectionView.bounds.size.width)/scrollView.bounds.size.width;
    
    if (isnan(progress) || (progress > -0.001 && progress < 0.001)) {
        return;
    }
    
    NSInteger index = (NSInteger)(scrollView.contentOffset.x / scrollView.bounds.size.width);
    
    if (self.collectionView.contentOffset.x > self.startOffsetX) {
        // 左滑动
        sourceIndex = index;
        targetIndex = index + 1;
        if (targetIndex > self.childVcs.count - 1) {
            return;
        }
    } else {
        // 右滑动
        sourceIndex = index + 1;
        targetIndex = index;
        progress = 1 - progress;
        if (targetIndex < 0) {
            return;
        }
    }
    
    // 通知代理
    if ([self.delegate respondsToSelector:@selector(contentViewWith:sourceIndex:targetIndex:progress:)]) {
        [self.delegate contentViewWith:self sourceIndex:sourceIndex targetIndex:targetIndex progress:progress];
    }
}

- (void)titleViewWith:(DSTitleView *)titleView currentIndex:(NSInteger)currentIndex
{
    self.isForbidDelegate = YES;
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:currentIndex inSection:0];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
